package cn.gov.cus.rmftquartz.common.ibmmq;

//import cn.ok.Config;
import com.google.common.collect.Lists;
import com.google.common.collect.Table;
import com.ibm.mq.MQEnvironment;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import com.ibm.msg.client.wmq.compat.base.internal.MQC;

import java.util.List;
import java.util.Map;

/**
 * 消息发送器
 * @author wxming
 *
 */
public class MsgSender {
	private static List<MQQueueManager> mqQueueManagers = Lists.newArrayList();
    private static List<MQQueue> mqQueues = Lists.newCopyOnWriteArrayList();

    //public MsgSender(String queueNames, String channels) throws Exception {
    public MsgSender(String queueNames,String channels,String HostName,String Port,String CCSID,String UserID,String PassWD,String QM_NAME) throws Exception {
        /*Config config = new Config("config.properties");

        MQEnvironment.hostname = config.getProperty("HostName");
        MQEnvironment.port = Integer.parseInt(config.getProperty("Port"));
        MQEnvironment.CCSID = Integer.parseInt(config.getProperty("CCSID"));
        MQEnvironment.userID = config.getProperty("UserID");
        MQEnvironment.password = config.getProperty("PassWD");*/
    	
        MQEnvironment.hostname = HostName;
        MQEnvironment.port = Integer.parseInt(Port);
        MQEnvironment.CCSID = Integer.parseInt(CCSID);
        MQEnvironment.userID = UserID;
        MQEnvironment.password = PassWD;

        Table<Integer, String, String> tbNameChannel = MsgReceiver.getQueueManager(queueNames, channels);

        MQQueue mqQueue;
        for (int i = 0; i < tbNameChannel.size(); i++) {
            for (Map.Entry<String, String> entry : tbNameChannel.row(i).entrySet()) {
                MQEnvironment.channel = entry.getValue();
                //MQQueueManager mqQueueManager = new MQQueueManager(config.getProperty("QM_NAME"));
                MQQueueManager mqQueueManager = new MQQueueManager(QM_NAME);
                mqQueue = mqQueueManager.accessQueue(entry.getKey(), MQC.MQOO_OUTPUT);
                mqQueues.add(mqQueue);
                mqQueueManagers.add(mqQueueManager);
            }
        }

        if (mqQueues.size() == 0) {
            throw new Exception("mqQueues.size() ==0");
        }
    }

    public List<MQQueue> getQueue() {
        return mqQueues;
    }

    public void close() {
        MsgReceiver.doClose(mqQueueManagers, mqQueues);
    }
}
